/** @jsx createElement */
import { View, Text, ScrollView, RefreshControl,Layout,Dialog,Button,Image,Input  } from 'nuke';
import {createElement, Component,render} from 'rax';
import {Http} from '$util/index';
const { MultiRow ,Grid,Col}  = Layout;
import CountdownPromV1 from '$components/CountdownPromV1/';
import ShopTitleV1 from '$components/ShopTitleV1/';
import CountdownItemsV1 from '$components/CountdownItemsV1/';
import SingleImage from '$components/SingleImage/';
import DoubleImages from '$components/DoubleImages/';
import TripleImages from '$components/TripleImages/';
window.__TPL__=[{"id":"10","mix":null,"code":"countdown_prom_v1","countdownId":"23","countdownNum":600,"countdownBg":"https:\/\/img.alicdn.com\/imgextra\/i3\/27390555\/O1CN01V6qyLo1FyEInEs7LJ_!!27390555.jpg","dialog":"true","dialogBg":"https:\/\/img.alicdn.com\/imgextra\/i1\/27390555\/O1CN01bzLFuz1FyEIcrvwma_!!27390555.jpg","passwd":"EtnV8"},{"id":"11","mix":null,"code":"countdown_items_v1","bgColor":"rgb(119, 10, 199)"}] || {}
let App = class Index extends Component {
    constructor() {
        super();
        this.state={
            isRefreshing: false,
            refreshText: '↓ 下拉刷新',
            data:[],
			countdown:0,
			countdownId:0,
			countdownBg:"",
			intervalId:0,
			pageSize:10,
			pageNum:1,
        }
    }
	componentWillMount(){
		for(let comp in window.__TPL__){
			const code = window.__TPL__[comp].code;
			if(code.indexOf("countdown_prom")>=0){
				this.setState({countdownId:window.__TPL__[comp].countdownId,
							   countdownBg:window.__TPL__[comp].countdownBg,
							   countdown:window.__TPL__[comp].countdownNum,
							   dialog:window.__TPL__[comp].dialog=="true",
							   dialogBg:window.__TPL__[comp].dialogBg,
							   passwd:window.__TPL__[comp].passwd
							   });
			}
		}
		let _self = this;
		Tida.mixNick(function (data) {
			_self.checkNick(data.data.mixnick);
		});
	}
	componentDidMount(){
		var _self = this;
		Http.fetch({
            name:'interface.page.get_promo_items',
            data:{page:1,pageSize:_self.state.pageSize,taskId:this.state.countdownId}
        }).then(function(res){
			_self.setState({data:res.data,total:parseInt(res.total)});
        });
	}
	getNick = e => {
		
		var _self = this;
		let nick = this.refs.inputnick.getValue();
		if(!nick){
			_self.setState({dialog_title:"提示信息",dialog_msg:"请输入营销密码，然后才能享用专属折扣哦！"});
			_self.refs.dialog.show();
			return;
		}
		if(nick==this.state.passwd){
			Tida.toast("正在准备数据...");
			Tida.mixNick(function (data) {
				let mixnick = data.data.mixnick;
				let openuid = '';
				Tida.user.openuid(function (d) {
					openuid = d.data.openuid;
					_self.startTask(openuid,nick,mixnick);
				}, function (d) {
				});
			});
		}else{
			_self.setState({dialog_title:"提示信息",dialog_msg:"请输入正确的营销密码哦！"});
			_self.refs.dialog.show();
		}
		// Tida.mixNick(function (data) {
			// let mixnick = data.data.mixnick;
			// if(mixnick.substr(0,1)!=nick.substr(0,1)){
				// _self.setState({dialog_title:"提示信息",dialog_msg:"请输入当前淘宝账号哦！"});
				// _self.refs.dialog.show();
				// return;
			// }
			
			// Tida.toast("正在准备数据...");
			// let openuid = '';
			// Tida.user.openuid(function (d) {
				// openuid = d.data.openuid;
				// _self.startTask(openuid,nick,mixnick);
			// }, function (d) {
			// });
		// });
		
    };
	checkNick(mixnick){
		var _self = this;
		Tida.toast("请稍候...");
		Http.fetch({
			name:'interface.page.check_nick',
			data:{mixnick,countdown_id:_self.state.countdownId}
		}).then(function(res){
			if(!res.data.log){
				_self.refs.input.show();
				return;
			}
			if(_self.state.dialog!="true" && !res.data.log){
				Tida.user.openuid(function (d) {
					openuid = d.data.openuid;
					_self.startTask(openuid,"",mixnick);
				}, function (d) {
				});
				return;
			}
			if(res.data.log && res.data.log.tag_action=="add"){
				let date = res.data.log.add_time;
				date = date.substring(0,19);  
				let add_time_ts = parseInt(new Date(date).getTime()/1000);
				let now_ts = parseInt(new Date().getTime()/1000);
				let countdownNew = _self.state.countdown-(now_ts - add_time_ts);
				countdownNew = countdownNew>0?countdownNew:0;
				_self.setState({countdown:countdownNew,dialog:false});
				_self.countdownRun();
				return;
			}
			if(res.data.log && res.data.log.tag_action=="del"){
				_self.setState({dialog_title:"提示信息",dialog_msg:"很抱歉，您已经享受过本次活动了。您还可以邀请朋友来参加哦！"});
				_self.refs.dialog.show();
				return;
			}
		});
	}
	startTask(openuid,nick,mixnick){
		var _self = this;
		Http.fetch({
			name:'interface.page.start_task',
			data:{openuid,nick,mixnick,countdown_id:_self.state.countdownId}
		}).then(function(res){
			if(res.data && res.data.log_id>0){
				_self.setState({dialog_title:"提示信息",dialog_msg:"很抱歉，您已经享受过本次活动了。您还可以邀请朋友来参加哦！"});
				_self.refs.dialog.show();
				return;
			}
			if(res.code && res.code!=200){
				_self.setState({dialog_title:"提示信息",dialog_msg:res.msg});
				_self.refs.dialog.show();
				return;
			}
			if(res.code && res.code==200){
				_self.refs.input.hide();
				_self.refs.modal1.show();
				setTimeout(function(){ 
					_self.countdownRun();
					_self.refs.modal1.hide();
				}, 3000);
			}
		});
	}
	closeInput=()=>{
		this.refs.input.hide();
	}
    handleRefresh=()=>{
        this.setState({
            isRefreshing: true,
            refreshText: '加载中',
        });
        //mock ajax
		
		var _self = this;
		Http.fetch({
            name:'interface.page.get_promo_items',
            data:{page:1,pageSize:_self.state.pageSize,taskId:this.state.countdownId}
        }).then(function(res){
			 _self.setState({
                isRefreshing: false,
                data: res.data,
                refreshText: '↓ 下拉刷新',
				pageNum:1
            });
        });
    }
    loadmore = ()=>{
        // 底部加载更多
		var _self = this;
		if(this.state.total>this.state.pageNum*this.state.pageSize){
			Http.fetch({
				name:'interface.page.get_promo_items',
				data:{page:_self.state.pageNum+1,pageSize:_self.state.pageSize,taskId:this.state.countdownId}
			}).then(function(res){
				_self.setState({
					data: _self.state.data.concat(res.data),
					pageNum:_self.state.pageNum+1
				});
			});
		}
    }
	hideDialog = ()=>{
		this.refs.dialog.hide();
	}
    hideModal = () => {
        this.refs.modal1.hide();
        this.refs.done.hide();
    }
    hideModalAndConfirm = () =>{
		this.countdownRun();
        this.refs.modal1.hide();
    }
	countdownRun = ()=>{
		let _self = this;
		if(_self.state.intervalId){
			clearInterval(_self.state.intervalId);
		}
		let i = setInterval(function(){
			if(_self.state.countdown<=0){
				clearInterval(_self.state.intervalId);
				_self.refs.done.show();
			}
			_self.setState({countdown:_self.state.countdown-0.1});
		},100);
		_self.setState({intervalId:i});
	}
	titleCase(str) {  
		return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());  
	}
	getComponents(){
		let doms = [];
		for(let comp in window.__TPL__){
			const code = window.__TPL__[comp].code;
			switch(code){
				case "single_image" :
					doms.push(<SingleImage
								text={window.__TPL__[comp]["myText"+window.__TPL__[comp].mix]}
								pic={window.__TPL__[comp]["myPic"+window.__TPL__[comp].mix]}
								link={window.__TPL__[comp]["myLink"+window.__TPL__[comp].mix]}
								/>);
				break;
				case "double_images" :
					doms.push(<DoubleImages
								setts={window.__TPL__[comp]}
								/>);
				break;
				case "triple_images" :
					doms.push(<TripleImages
								setts={window.__TPL__[comp]}
								/>);
				break;
				case "countdown_prom_v1":
					doms.push(<CountdownPromV1 
								countdown={this.state.countdown}
								limit={this.state.countdown}
								limitColor="#FFFFFF"
								countdownColor="#ffe553"
								img={this.state.countdownBg}
								/>);
				break;
				case "shop_title_v1":
					doms.push (<ShopTitleV1 
								setts={window.__TPL__[comp]}
								/>);
				break;
				case "countdown_items_v1":
					doms.push(<CountdownItemsV1 
								data={this.state.data}
								countdownNum={this.state.countdown}
								bgColor={window.__TPL__[comp]["bgColor"]}
								/>);
				break;
			}
		}
		return doms;
	}
    render() {
        return (
            <ScrollView ref="vscroller" style={styles.vscroller} onEndReachedThreshold={1} onEndReached={this.loadmore}>
                <RefreshControl refreshing={this.state.isRefreshing} style={[styles.itemRefresh]} onRefresh={this.handleRefresh}>
                    <Text style={{fontSize:"28rem",color:"#3089dc"}}>{this.state.refreshText}</Text>
                </RefreshControl>
				<Dialog ref="modal1" duration={1000} visible={false} contentStyle={styles.modalStyle}>
                    <View style={styles.body}>
                        <View style={{alignItems:'center'}}>
							<Image
							style={{ width:200,height:200}}
							src="https://img.alicdn.com/imgextra/i4/27390555/O1CN01MJaLH61FyEICPoPvU_!!27390555.gif"
							/>
						</View>
                        <View style={styles.head}><Text>精彩马上开始</Text></View>
                    </View>
					{/*
                    <View style={styles.footer}>
                        <Button style={styles.dlgBtn} type="normal" onPress={this.hideModal}>取消</Button>
                        <Text style={styles.dlgBtnSeperator}>|</Text>
                        <Button style={styles.dlgBtn} type="normal" onPress={this.hideModalAndConfirm}>确定</Button>
                    </View>
					*/}
                </Dialog>
				
				<Dialog ref="input" duration={1000} visible={this.state.dialog} contentStyle={{...styles.inputStyle,backgroundImage:"url("+this.state.dialogBg+")"}}>
					<View style={styles.inputView}>
						<Input preventEnterKey placeholder="请输入营销密码" returnKeyType="done" ref="inputnick" style={styles.inputText} />
						<Button type="normal" style={styles.inputButton} onPress={this.getNick}></Button>
					</View>
					<View style={styles.inputCloseView}>
						<Image
							style={{ width:"60rem",height:"60rem"}}
							src="https://img.alicdn.com/imgextra/i3/27390555/O1CN01FppeXM1FyEIdZpEDS_!!27390555.gif"
							onClick={this.closeInput}
							/>
					</View>
                </Dialog>
				<Dialog ref="done" duration={1000} contentStyle={styles.modalStyle}  onMaskPress={this.onMaskPress}>
                    <View style={styles.body}>
                        <View style={styles.head}><Text style={styles.textHead}>结束了</Text></View>
                        <View style={styles.tips}><Text style={styles.text}>真抱歉，这次活动结束了。请再接再厉，下次不要错过哦！当然，您还可以邀请别人参加，记住，机会只有1次</Text></View>
                    </View>
                    <View style={styles.footer}>
                        <Button style={styles.dlgBtn} type="normal" onPress={this.hideModal}>取消</Button>
                        <Text style={styles.dlgBtnSeperator}>|</Text>
                        <Button style={styles.dlgBtn} type="normal" onPress={this.hideModal}>确定</Button>
                    </View>
                </Dialog>
				
				<Dialog ref="dialog" duration={1000} visible={false} contentStyle={styles.modalStyle}>
                    <View style={styles.body}>
                        <View style={styles.head}><Text style={styles.textHead}>{this.state.dialog_title}</Text></View>
                        <View style={styles.tips}><Text style={styles.text}>{this.state.dialog_msg}</Text></View>
                    </View>
                    <View style={styles.footer}>
                        <Button style={styles.dlgBtn} type="normal" onPress={this.hideDialog}>取消</Button>
                        <Text style={styles.dlgBtnSeperator}>|</Text>
                        <Button style={styles.dlgBtn} type="normal" onPress={this.hideDialog}>确定</Button>
                    </View>
                </Dialog>
					{this.getComponents()}
				<Text style={{fontSize:"28rem",color:"#666666",textAlign:"center"}}>本活动由微折提供技术支持</Text>
            </ScrollView>

        )
    }
}
const styles={
    vscroller:{
        flex:1,
    },
	countdown:{
		fontSize:"200rem",
		textAlign:"center"
	},
    itemRefresh:{
        width:750,
        height:100,
        alignItems:'center',
        justifyContent:'center',

    },
    item:{
        height:'300rem',
        alignItems:'center',
        justifyContent:'center',
    },
  wrapper: {
    paddingLeft: '24rem',
    paddingRight: '24rem',
    paddingTop: '24rem',
    backgroundColor:'#f4f4f4'
  },
  click: {
    height: '100rem',
    lineHeight: '100rem',
    textAlign: 'center',
    borderWidth: '1rem',
    borderStyle: 'solid',
    borderColor: '#ccc'
  },
  modalStyle: {
    width: '540rem',
    height: '350rem',
    borderTopColor:'#FF9000',
    borderTopStyle:'solid',
    borderTopWidth:'8rem',
    // padding:'10rem',
    borderRadius:'8rem',
  },
  inputStyle:{
    width: '578rem',
    height: '898rem',
    borderRadius:'20rem',
	backgroundImage:"url(https://img.alicdn.com/imgextra/i1/27390555/O1CN01bzLFuz1FyEIcrvwma_!!27390555.jpg)",
	backgroundSize:"100% 100%"
  },
  inputView:{
	  width:"578rem",
	  marginTop:"450rem",
	  fontSize:"20rem",
	  justifyContent: 'center',
  },
  inputText:{
	  borderWidth: 0,
	  height: 60,
	  width:"320rem",
	  marginLeft:"160rem",
	  fontSize:"26rem",
  },
  inputButton:{
	backgroundColor:"none",
	color:'#944300',
	borderColor:"#FFFFFF",
    borderRadius:'30rem',
	width:450,
	height:72,
	marginTop:"30rem"
  },
  inputCloseView:{
	  marginTop:"290rem",
	  textAlign:"center",
	  width:"578rem",
     alignItems:'center'
  },
  body: {
    flex:1,
    paddingLeft:40,
    paddingRight:40,
    paddingTop:30,
    // justifyContent: 'center',
    borderRadius:'8rem',
    backgroundColor: '#ffffff',
  },
  head:{
    height: 50,
    alignItems: 'center',
    justifyContent: 'center',
  },
  textHead:{
    color:'#3d4145',
    fontSize:32,
  },
  tips:{
	paddingTop:"20rem"
  },
  text:{
    fontSize:'28rem',
    lines:3,
    [`-webkit-line-clamp`]: 3,
    overflow: 'hidden',
    height:'120rem',
    lineHeight:'40rem',
    color:'#60646e',
    textOverflow:'ellipsis'
  },
  footer: {
    borderTopColor:'#dddddd',
    flexDirection:'row',
    borderTopStyle:'solid',
    borderTopWidth:1,
    alignItems: 'center',
    justifyContent: 'flex-end',
    height: '94rem'
  },
  dlgBtn:{
    flex:1,
    borderWidth:0,
    borderColor:'#FFFFFF',
    color:'#FF9000'
  },
  dlgBtnSeperator:{
    color:'#dddddd'
  }
}
render(<App/>);

